from fastapi import APIRouter, Depends, HTTPException, Header
from sqlalchemy.orm import Session
from typing import Any, Optional 
from app.core.security import verify_token, verify_source, generate_token
from app.crud import asphalt as crud
from app.schemas.asphalt import AsphaltMixingDataCreate
from app.api.deps import get_db

router = APIRouter()

@router.get("/token", summary="获取访问令牌")
async def get_token(source: str = Header(..., description="数据来源")):
    """
    获取访问令牌
    
    - **source**: 数据来源标识，需要在请求头中提供
    """
    try:
        if source not in ["djgk-sjk"]:  # 验证数据来源
            raise HTTPException(status_code=400, detail="无效的数据来源")
        token = generate_token(source)
        return {
            "code": 200,
            "msg": "Token生成成功",
            "data": {
                "token": token,
                "expires_in": 24 * 60 * 60  # 24小时的秒数
            }
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Token生成失败: {str(e)}")

@router.post("/receive/hcdata", summary="沥青拌和站数据接收")
async def receive_data(
    data: AsphaltMixingDataCreate,
    
    db: Session = Depends(get_db),
    token: str = Depends(verify_token),
    source: str = Header(..., description="数据来源标识")  # 改为必需的 header
) -> Any:
    try:
        data_dict = data.model_dump()
        data_dict["source"] = source
        crud.create_asphalt_data(db=db, data=data_dict)
        return {"code": 200, "msg": "数据保存成功"}
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"数据保存失败: {str(e)}"
        ) 